# -*- coding: utf-8  -*-
#!/usr/local/bin/python

__author__ = 'jian.yao'

from misc.errorcode import ERROR_CODE, ERROR_MESSAGE
from sso.Token.models import Token, genKey, calExpireTime
import time
def get_token(uid):
    try:
        token = Token.objects.get(uid = uid)
        if(token.isExpired()):
            return refresh_token(uid)
        else:
            return token, ERROR_CODE.SUCCESS, ERROR_MESSAGE.SUCCESS
    except Token.DoesNotExist:
        return create_token(uid)

def refresh_token(uid):
    try:
        t = Token.objects.get(uid = uid)
        token = genKey('token', 8)
        t.token = token
        now = time.time()
        t.createTime = now
        t.expireTime = calExpireTime(now)
        t.save()
        return token, ERROR_CODE.SUCCESS, ERROR_MESSAGE.SUCCESS
    except Token.DoesNotExist:
        return create_token(uid)

def create_token(uid):
    if(Token.objects.filter(**{'uid':uid}).exists()):
        return None, ERROR_CODE.USERNAME_ALREADY_EXIST, ERROR_MESSAGE.USERNAME_ALREADY_EXIST
    else:
        token = Token.objects.create_token(uid)
        return token, ERROR_CODE.SUCCESS, ERROR_MESSAGE.SUCCESS

